<template>
  <el-form ref="form" :model="form" label-width="80px" size="small">
    <el-form-item label="多边形">
      <el-input v-model="form.polygon" type="textarea" rows="5" placeholder="请输入内容"></el-input>
    </el-form-item>
    <el-form-item label="示例">
      <el-input :value="polygonPlaceholder" readonly type="textarea" rows="5" placeholder="请输入内容"></el-input>
    </el-form-item>
    <el-form-item label="图片">
      <el-upload :on-change="handleChangeFile" :auto-upload="false" class="upload-demo" action="image/*">
        <el-button size="small" type="default">点击上传</el-button>
      </el-upload>
      <div style="color:#999;font-size:12px;text-align:left;line-height:16px">文件格式：jpg/png/gif/tif/tiff</div>
    </el-form-item>
    <el-form-item label="自动旋转">
      <el-radio v-model="isRote" :label="1">是</el-radio>
      <el-radio v-model="isRote" :label="0">否</el-radio>
    </el-form-item>
    <div class="text-right">
      <el-button @click="drawData" type="primary" size="mini">数据绘制</el-button>
      <el-button @click="drawAction" type="primary" size="mini">打点绘制</el-button>
      <el-button @click="loadImage" size="mini" type="primary">载入图片</el-button>
    </div>
  </el-form>
</template>

<script>
import * as Cesium from 'cesium'
import { DrawPolygon } from '@/components/dogeo/cesium/draw/draw-polygon.js'
import { Cartesian3_to_WGS84, courseAngle } from '@/components/dogeo/cesium/transform.js'
import imager from '@/components/dogeo/cesium/image.js'

export default {
  name: 'tool-draw',

  props: {
    viewer: {
      type: Object,
      default () {
        return null
      }
    }
  },

  data () {
    return {
      form: {
        polygon: ''
      },
      polygonPlaceholder: '[[115.85874485296023,39.90345696354634],[116.37067803539018,40.344532256885074],[117.20643905468796,39.772847504291725],[116.71283928748771,39.32769138373433]]',
      file: null,
      isRote: 1
    }
  },

  methods: {
    // 手动打点绘制
    drawAction () {
      if (!this.viewer) {
        return true
      }
      if (!this.recter) {
        this.recter = new DrawPolygon({
          viewer: this.viewer,
          Cesium,
          callback: () => {
            // 范围
            let rects = []
            if (this.recter) {
              rects = this.recter.getData() || []
            }
            rects = rects.map(cartesian3 => {
              let wgs84 = Cartesian3_to_WGS84(cartesian3)
              return wgs84
            })
            rects = rects.map(item => {
              return '[' + item.lng + ',' + item.lat + ']'
            }).join(',')
            this.form.polygon = '[' + rects + ']'
            this.recter.destroy()
          }
        })
      }
      this.recter.startCreate()
    },
    // 数据绘制
    drawData () {
      if (!this.viewer) {
        return true
      }
      this.drawDataPolygon()
    },
    // 获取多边形点数据
    getPolygonData () {
      if (!/\[/.test(this.form.polygon)) {
        this.$message({
          message: '请按示例输入绘制数据',
          type: 'error'
        })
        return false
      }
      return JSON.parse(this.form.polygon)
    },
    // 根据数据画多边形
    drawDataPolygon () {
      let points = this.getPolygonData()
      if (!points) {
        return false
      }
      let cartesian3s = points.map(item => {
        return Cesium.Cartesian3.fromDegrees(item[0], item[1], item[2] || 1)
      })
      this.viewer.entities.add({
        name: 'polygon',
        polygon: {
          hierarchy: new Cesium.PolygonHierarchy(cartesian3s),
          material: Cesium.Color.RED
        }
      })
      this.viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(points[0][0], points[0][1], 1000),
        orientation: {
          heading: Cesium.Math.toRadians(0), // 水平偏角，默认正北 0
          pitch: Cesium.Math.toRadians(-90), // 俯视角，默认-90，垂直向下
          roll: 0, // 旋转角
        }
      })
    },
    handleChangeFile (file, fileslist) {
      if (fileslist.length > 1) {
        fileslist.shift()
      }
      this.file = file.raw
    },
    // 载入图片
    loadImage () {
      if (!this.file) {
        this.$message({
          type: 'error',
          message: '未上传图片'
        })
        return true
      }
      if (!/\.gif|png|jpe?g|\.bmp|tif+/i.test(this.file.name)) {
        this.$message({
          type: 'error',
          message: '请上传图片'
        })
        return true
      }
      let points = this.getPolygonData()
      if (!points) {
        return false
      }

      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      let defer = null
      if (/tiff?$/i.test(this.file.name)) {
        defer = imager.tiffToImageByGeotiff(this.file)
      } else {
        defer = this.fileToBase64(this.file)
      }
      defer.then(url => {
        this.loadModelImage(url, points)
      }).finally(() => {
        loading.close()
      })
    },
    loadModelImage (url, points) {
      let viewer = this.viewer
      if (this.entity) {
        viewer.entities.remove(this.entity)
        this.entity = null
      }
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      try {
        let cartesian3s = points.map(item => {
          return Cesium.Cartesian3.fromDegrees(item[0], item[1], item[2] || 1)
        })
        let entity = viewer.entities.add({
          name: 'image',
          polygon: {
            hierarchy: new Cesium.PolygonHierarchy(cartesian3s),
            material: url
          }
        })
        if (this.isRote) {
          let degree = courseAngle(points[0][0], points[0][1], points[1][0], points[1][1])
          entity.polygon.stRotation = Cesium.Math.toRadians(360 - degree)
        }
        this.entity = entity
      } catch (error) {
        console.log(error)
      } finally {
        setTimeout(() => {
          loading.close()
        }, 500)
      }
      viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(points[0][0], points[0][1], 1000),
        orientation: {
          heading: Cesium.Math.toRadians(0), // 水平偏角，默认正北 0
          pitch: Cesium.Math.toRadians(-90), // 俯视角，默认-90，垂直向下
          roll: 0, // 旋转角
        }
      })
    },
    fileToBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => resolve(reader.result)
        reader.onerror = (error) => reject(error)
      })
    },
    // 清除
    clear () {
      let list = [...this.viewer.entities.values]
      list.map((item) => {
        //if (/polygon/.test(item.name)) {
          this.viewer.entities.remove(item)
        //}
      })
    }
  }
}
</script>